package com.alan.netty;

import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.util.ReferenceCountUtil;

/**
 * 处理服务器通道
 * Created by Alan on 2017/8/9.
 */
public class DiscardServerHandler extends ChannelInboundHandlerAdapter {// 1

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {///2
        ByteBuf in = (ByteBuf) msg;
        try {
            while (in.isReadable()) { // (1)
                System.out.print((char) in.readByte());
                System.out.flush();
            }
        } finally {
            ReferenceCountUtil.release(msg); // (2)
        }
        // 或者直接打印
       // System.out.println("Yes, A new client in = " + ctx.name());
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {//4
        //出现异常时关闭连接
        cause.printStackTrace();
        ctx.close();
    }
}